package com.gy.assistant.ui.chat.room;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import im.zego.zim.ZIM;
import im.zego.zim.callback.ZIMRoomOnlineMemberCountQueriedCallback;
import im.zego.zim.entity.ZIMCommandMessage;
import im.zego.zim.entity.ZIMCustomMessage;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMMessage;
import im.zego.zim.entity.ZIMMessageSendConfig;
import im.zego.zim.entity.ZIMTextMessage;
import im.zego.zim.enums.ZIMConversationType;
import im.zego.zim.enums.ZIMMessagePriority;
import com.gy.assistant.R;
import com.gy.assistant.SDKManager;
import com.gy.assistant.enums.ChatItemType;
import com.gy.assistant.entity.MessageInfo;
import com.gy.assistant.ui.chat.base.ZIMChatBaseActivity;

public class ZIMRoomChatActivity extends ZIMChatBaseActivity implements SDKManager.OnReceiveRoomMessage {

    public static HashMap<String, String> RoomOwnerMap = new HashMap<>();

    public static void actionStart(Activity loginActivity, String roomID, String roomName,String draft) {
        Intent intent = new Intent(loginActivity, ZIMRoomChatActivity.class);
        intent.putExtra("conversationID", roomID);
        intent.putExtra("conversationName", roomName);
        intent.putExtra("draft", draft);
        loginActivity.startActivity(intent);
    }

    private String TAG = "ZIMRoomChatActivity";
    private String conversationID;
    private static final int QUERY_ROOM_MESSAGE_COUNT = 30;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.group_detail, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override

    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                break;
            case R.id.group_detail:
                ZIMRoomMemberActivity.actionStart(this, conversationID);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.zimConversationType = ZIMConversationType.ROOM;

        conversationID = getIntent().getStringExtra("conversationID");
        setTitle(getRoomName());

        // 查询房间人数
        SDKManager.sharedInstance().queryRoomOnlineMemberCount(conversationID, new ZIMRoomOnlineMemberCountQueriedCallback() {
            @Override
            public void onRoomOnlineMemberCountQueried(String roomID, int count, ZIMError errorInfo) {
                setTitle(String.format("%s (%d)", getRoomName(), count));
            }
        });

        SDKManager.sharedInstance().addReceiveRoomMessageCallback(this);
        SDKManager.sharedInstance().queryRoomMessage(conversationID, null, QUERY_ROOM_MESSAGE_COUNT, true, this);
        SDKManager.sharedInstance().setRoomOnlineMemberCountCallback(new SDKManager.OnRoomOnlineMemberCountCallback() {
            @Override
            public void onRoomOnlineMemberCount(ZIM zim, int memberCount) {
                setTitle(String.format("%s (%d)", getRoomName(), memberCount));
            }
        });

    }

    private String getRoomName() {
        String roomName = getIntent().getStringExtra("roomName");
        if (roomName != null && !"".equals(roomName)) {
            return roomName;
        } else {
            return conversationID;
        }
    }

    public void sendMsg(String content) {
        if ("".equals(content.replace(" ", ""))) {
            Toast.makeText(ZIMRoomChatActivity.this, "Please enter valid content", Toast.LENGTH_LONG).show();
            return;
        }

        ZIMMessageSendConfig zimMessageSendConfig = new ZIMMessageSendConfig();
        zimMessageSendConfig.priority = ZIMMessagePriority.LOW;

        CheckBox cbCommand = findViewById(R.id.isCommand);
        CheckBox cbCustom = findViewById(R.id.isCustom);
        ZIMMessage zimMessage;

        if (cbCommand.isChecked()) {
            ZIMCommandMessage commandMessage = new ZIMCommandMessage();
            commandMessage.message = content.getBytes(StandardCharsets.UTF_8);

            zimMessage = commandMessage;
        }else if (cbCustom.isChecked()){
            ZIMCustomMessage customMessage = new ZIMCustomMessage(content, 100);
            customMessage.searchedContent="searchContent";
            zimMessage = customMessage;
        } else {
            ZIMTextMessage zimTextMessage = new ZIMTextMessage();
            zimTextMessage.message = content;
            zimMessage = zimTextMessage;
        }
        setMessageMention(zimMessage);
        SDKManager.sharedInstance().sendRoomMessage(zimMessage, conversationID, zimMessageSendConfig, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
        SDKManager.sharedInstance().leaveRoom(conversationID);
        SDKManager.sharedInstance().removeReceiveRoomMessageCallback(this);
    }


    @Override
    protected void onLoadMsg() {
        super.onLoadMsg();
        MessageInfo info = chatContentAdapter.getMessage(0);
        if (info != null) {
            SDKManager.sharedInstance().queryRoomMessage(conversationID, info.getZIMMessage(), QUERY_ROOM_MESSAGE_COUNT, true, this);
        }
    }

    @Override
    public void onReceiveRoomMessage(ZIM zim, ArrayList<ZIMMessage> messageList, String fromRoomID) {
        Collections.reverse(messageList);
        for (ZIMMessage message : messageList) {
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_LEFT);
            messageInfo.setZIMMessage(message);
            addMsg(messageInfo);
        }
    }

    @Override
    public void onMessageQueried(String convID, ZIMConversationType type, ArrayList<ZIMMessage> arrayList, ZIMError zimError) {
        super.onMessageQueried(convID, type, arrayList, zimError);
        Collections.reverse(arrayList);
        for (ZIMMessage message : arrayList) {
            MessageInfo messageInfo = new MessageInfo();
            if (message.getSenderUserID().equals(SDKManager.sharedInstance().zimUserInfo.userID)) {
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_RIGHT);
            } else {
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_LEFT);
            }
            messageInfo.setZIMMessage(message);
            addMsgToTop(messageInfo);
        }
    }

}
